﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.alipay.AlipayCenter;
import com.kuanter.kuanterauto.alipay.AlixId;
import com.kuanter.kuanterauto.alipay.BaseHelper;
import com.kuanter.kuanterauto.alipay.OrderInfoUtil;
import com.kuanter.kuanterauto.alipay.ResultChecker;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.utils.Utility;
import com.kuanter.kuanterauto.wapalipay.WapPayActivity;
import com.umeng.analytics.MobclickAgent;
/**
 * 移动充值
 * @author kuanter
 *
 */
public class RechargeActivity extends WuyangBaseActivity {
	private static final int WAP = 0;
	private LayoutInflater inflater;
	private View contentView;
	public String card_number;
	private TextView tv_card_number;
	private View choose_card;
	private ListView lvListView;
	private List<String> strCredits = new ArrayList<String>();
	private String chooseed_credits;
	private String whichActivityFlag ;
	private Intent intent = new Intent();
	private TextView choosed_credits_tv;
	private TextView alipay_wap;
	private TextView alipay_app;
	private View choose_credits_goto;
	private String flag;
	private Button back_btn;
	private TextView money_tv;
	
	private AlipayCenter alipayCenter;
	private boolean isPrepare;
	private boolean isCheckForPartnerAndSeller;
	private Activity activity = RechargeActivity.this;
	
	
	// 这里接收支付结果，支付宝手机端同步通知
		private Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				try {
					String strRet = (String) msg.obj;

					Log.e(TAG, strRet); // strRet范例：resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}
					switch (msg.what) {
					case AlixId.RQF_PAY: {
						//
						alipayCenter.closeProgress();

						BaseHelper.log(TAG, strRet);

						// 处理交易结果
						try {
							// 获取交易状态码，具体状态代码请参看文档
							String tradeStatus = "resultStatus={";// 无多大意义
							int imemoStart = strRet.indexOf("resultStatus=");
							imemoStart += tradeStatus.length();
							int imemoEnd = strRet.indexOf("};memo=");
							tradeStatus = strRet.substring(imemoStart, imemoEnd);

							// 先验签通知
							ResultChecker resultChecker = new ResultChecker(strRet);
							int retVal = resultChecker.checkSign();
							// 验签失败
							if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
								BaseHelper.showDialog(
										activity,
										"提示",
										getResources().getString(
												R.string.check_sign_failed),
										android.R.drawable.ic_dialog_alert);
							} else {// 验签成功。验签成功后再判断交易状态码
								if (tradeStatus.equals("9000")){// 判断交易状态码，只有9000表示交易成功
									ProApplication.getInstance().setCardInfoList(null);
									BaseHelper.showDialog(activity, "提示",
											"支付成功",
											R.drawable.infoicon);
									Intent data = new Intent();
//									data.putExtra("chooseed_credits", chooseed_credits);
									setResult(255, data );
								}else{
									BaseHelper.showDialog(activity, "提示",
											"支付失败",
											R.drawable.infoicon);
								}
									
							}

						} catch (Exception e) {
							e.printStackTrace();
							BaseHelper.showDialog(activity, "提示", "取消",
									R.drawable.infoicon);
						}
					}
						break;
					}

					super.handleMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		private ProApplication application;
		private SelecterGradePopupWindow menuWindow;
		private SelecterGradePopupWindow menuWindow2;
		private DataLoader dataLoader;
		private List<CardInfo> cardInfos;
		Handler handler2 = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case HttpTask.RESULT_OK:
					finishProgress();
//					String result = msg.getData().getString("result");
					String result = (String) msg.obj;
					if (!result.equals("网络连接错误")) {
						try {
							if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
																// 字段值是否为false
								com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
										.parseObject(result);
								if(null != jsonObjectResult
										.getString("cardInfoList")){
									String JsonStringUserInfo = jsonObjectResult
											.getString("cardInfoList");
									cardInfos = JSON.parseArray(
											JsonStringUserInfo, CardInfo.class);
									// 将cardInfoList缓存
									ObjectCache.set("cardInfoList", cardInfos);
									application.setCardInfoList(cardInfos);
									for(int i=0;i<cardInfos.size();i++){
										if("2".equals(cardInfos.get(i).getState())){
											cardNumberList.add(cardInfos.get(i).getCardNumber());
										}
									}
									menuWindow2 = new SelecterGradePopupWindow(RechargeActivity.this, new MyPopListViewClick(), cardNumberList);
								}else {
									showToast("挂失成功");
								}
								finishProgress();
							} else {
								finishProgress();
								// 显示返回数据中 errorMsg 字段值
								showToast("失败");
							}
						} catch (JSONException e) {
							finishProgress();
							showToast("登录失败");
							e.printStackTrace();
						}
					} else {
						finishProgress();
						showToast("登录失败,网络错误!");
					}
					break;
				case HttpTask.RESULT_ERROR:
					finishProgress();
					showToast("网络错误!");
					break;
				}
			}
		};
		Handler handler3 = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case HttpTask.RESULT_OK:
					finishProgress();
					String result = (String) msg.obj;//{"orderNo":"CZ20130524155046","status":true}
					if (!result.equals("网络连接错误")) {
						try {
							if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
																// 字段值是否为false
								com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
										.parseObject(result);
								String orderNo = jsonObjectResult.getString("orderNo");
								String orderInfo = OrderInfoUtil.getOrderInfo(orderNo, "宽途卡充值"+tv_card_number.getText().toString(),
										"宽途汽车",chooseed_credits);
								boolean payResult = alipayCenter.payStart(orderInfo, mHandler);
								if(payResult){
									CardAndAccountActivity.flag = 200;
								}else {
									CardAndAccountActivity.flag = 0;
								}
								finishProgress();
							} else {
								finishProgress();
								// 显示返回数据中 errorMsg 字段值
								showToast("失败");
							}
						} catch (JSONException e) {
							finishProgress();
							showToast("登录失败");
							e.printStackTrace();
						}
					} else {
						finishProgress();
						showToast("登录失败,网络错误!");
					}
					break;
				case HttpTask.RESULT_ERROR:
					finishProgress();
					showToast("网络错误!");
					break;
				}
			}
		};
		private int userId;
		public View inputView;
		public EditText input_jine_et;
		public AlertDialog alertDialog;
		private static ArrayList<String> cardNumberList;
		
		public void onResume() {
		    super.onResume();
		    MobclickAgent.onResume(this);
		}
		public void onPause() {
		    super.onPause();
		    MobclickAgent.onPause(this);
		}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recharge);
		//注册广播
		IntentFilter filter = new IntentFilter("input");
		registerReceiver(new MyBroadcastReceiver(), filter );
		///////////////////////////
		application = (ProApplication)getApplication();
		userId = SharePrefenceUtil.getUserID(this);
		//因为充值界面会由多个界面跳转而来所以在此要做区分
		whichActivityFlag = getIntent().getStringExtra("comeFromWhichActivity");
		if("CardAndAccountActivity".equals(whichActivityFlag)){
			card_number = getIntent().getStringExtra("card_number");
		}else {
			card_number = null;
		}
		inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		strCredits.add("50");
		strCredits.add("100");
		strCredits.add("200");
		strCredits.add("500");
		strCredits.add("其他金额");
		menuWindow = new SelecterGradePopupWindow(RechargeActivity.this, new MyPopListViewClick(),strCredits);
		cardNumberList = new ArrayList<String>();
//		if(null == application.getCardInfoList()){
			this.downLoadCardInfos();
		/*}else {
			for(int i=0;i<application.getCardInfoList().size();i++){
				cardNumberList.add(application.getCardInfoList().get(i).getCardNumber());
			}
			menuWindow2 = new SelecterGradePopupWindow(RechargeActivity.this, new MyPopListViewClick(), cardNumberList);
		}*/
	}

	private void downLoadCardInfos() {
		dataLoader = new DataLoader(this);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//从SharedPreferences本地化数据中区账号信息
		params.add(new BasicNameValuePair("cardInfo.userId",userId+""));
		dataLoader.DisplayData(MainConstants.HOST_test
				+ HttpConfigAPI.QUERY_CARD, params, handler2, "", false);
		showProgress("正在加载数据...");
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		this.getControlViewText();
		switch (v.getId()) {
		case R.id.alipay_app:
			// 调用支付接口,支付成功通知服务器页面，支付成功，并将积分设置
			
			if(null == card_number){
				showToast("请选择卡片");
			}else if("".equals(chooseed_credits)){
				showToast("请选择需要充值多少积分");
			}else {
				alipayCenter = new AlipayCenter(this); 
				isPrepare = alipayCenter.payPrepareForcheckInstallAlipay();
				if (isPrepare) {
					/*isCheckForPartnerAndSeller = alipayCenter
							.checkInfoForPartnerAndSeller();
					if (isCheckForPartnerAndSeller) {*/
						dataLoader = new DataLoader(this);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("cardNumber",card_number));
						params.add(new BasicNameValuePair("rechargeAmount",chooseed_credits));
						dataLoader.DisplayData(MainConstants.HOST_test
								+ HttpConfigAPI.ORDER, params, handler3, "", false);
						showProgress("正在加载数据...");
//					}
				}
			}
			
			break;
		case R.id.alipay_wap:
			// 调用支付接口,支付成功通知服务器页面，支付成功，并将积分设置
						ProApplication.getInstance().setCardInfoList(null);
						if(null == card_number){
							showToast("请选择卡片");
						}else if("".equals(chooseed_credits)){
							showToast("请选择需要充值多少积分");
						}else {
							intent.putExtra("cardNumber", card_number);
							intent.putExtra("rechargeAmount", chooseed_credits);
							intent.setClass(RechargeActivity.this, WapPayActivity.class);
							startActivity(intent);
							CardAndAccountActivity.flag = 200;		
						}
			break;
		case R.id.back_btn:
			this.finish();
			break;
		case R.id.choose_card:

			flag = "choose_card";
			/*contentView = inflater.inflate(R.layout.popup_window_list, null);
			lvListView = (ListView) contentView
					.findViewById(R.id.lv_car_number);
			lvListView.setAdapter(new ArrayAdapter<String>(this,
					R.layout.popup_window_list_item, R.id.tv_car_number, strs));
			lvListView.setOnItemClickListener(new MyPopListViewClick());
			popupWindow = new PopupWindow(contentView,
					LayoutParams.FILL_PARENT, 200);
			// popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.holo_blue_bright))
			// ;
			popupWindow.setFocusable(true);
			popupWindow.showAsDropDown((View)alipay_wap);
					*/
			menuWindow2.showAtLocation(RechargeActivity.this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.choose_credits_goto:
			flag = "choose_credits_goto";
			
			/*contentView = inflater.inflate(R.layout.popup_window_list, null);
			lvListView = (ListView) contentView
					.findViewById(R.id.lv_car_number);
			lvListView.setAdapter(new ArrayAdapter<String>(this,
					R.layout.popup_window_list_item, R.id.tv_car_number, strs));
			lvListView.setOnItemClickListener(new MyPopListViewClick());
			popupWindow = new PopupWindow(contentView,
					LayoutParams.FILL_PARENT, 200);
			// popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.holo_blue_bright))
			// ;
			popupWindow.setFocusable(true);
			popupWindow.showAsDropDown((View)alipay_wap);*/
            menuWindow.showAtLocation(RechargeActivity.this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		default:
			break;
		}
	}
	//自定义广播
	private class MyBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			InputMethodManager m = (InputMethodManager)
					RechargeActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                            m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		}
		
	}

	public class MyPopListViewClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if("choose_credits_goto".equals(flag)){
				
				if(strCredits.get(position).equals("其他金额")){
					inputView = View.inflate(RechargeActivity.this, R.layout.input_view, null);
					input_jine_et = (EditText)inputView.findViewById(R.id.input_jine_et);
					AlertDialog.Builder builder = new AlertDialog.Builder(RechargeActivity.this)
					.setView(inputView)
					.setMessage("请输入充值金额")
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(!input_jine_et.getText().toString().trim().equals("")){
								if(Integer.valueOf(input_jine_et.getText().toString().trim())>=50){
									chooseed_credits = input_jine_et.getText().toString();
									choosed_credits_tv.setText(input_jine_et.getText().toString());
									money_tv.setText(input_jine_et.getText().toString());
								}else {
									showToast("最小充值金额为50元"); 
								}
							}else {
								showToast("请输入充值金额");
							}
						}
					}).setNegativeButton("取消", null);
					builder.create().show();
					//发送广播显示输入法
					Intent intent = new Intent("input");
					sendBroadcast(intent);
				}else{
					chooseed_credits = strCredits.get(position);
					choosed_credits_tv.setText(chooseed_credits);
					money_tv.setText(chooseed_credits);
				}
				menuWindow.dismiss();
//				money_tv.setText(Double.valueOf(chooseed_credits)*1.0+"");
			}else{
				card_number = cardNumberList.get(position);
				tv_card_number.setText(card_number);
				menuWindow2.dismiss();
			}
			
		}

	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		tv_card_number = (TextView) this.findViewById(R.id.card_number);
		choose_card = this.findViewById(R.id.choose_card);
		choosed_credits_tv = (TextView) this.findViewById(R.id.choosed_credits);
		//wap pay
		//choose credits 
		choose_credits_goto = this.findViewById(R.id.choose_credits_goto);
		back_btn = (Button)this.findViewById(R.id.back_btn);
		//pay
		alipay_app = (TextView)this.findViewById(R.id.alipay_app);
		alipay_wap = (TextView)this.findViewById(R.id.alipay_wap);
		money_tv = (TextView)this.findViewById(R.id.money_tv);
		money_tv.setText("0.00");
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		choose_card.setOnClickListener(this);
		choose_credits_goto.setOnClickListener(this);
		back_btn.setOnClickListener(this);
		alipay_app.setOnClickListener(this);
		alipay_wap.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		tv_card_number.setText(card_number);
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		chooseed_credits = choosed_credits_tv.getText().toString();
	}

	public class SelecterGradePopupWindow extends PopupWindow {


		private TextView btn_cancel;
		private View mMenuView;
		
		ListView insuranceview;
		LayoutInflater inflater;
		
		PopInsuranceAdapter adapter;
		
		List<String> ci_pop;

		public SelecterGradePopupWindow(Activity context,OnItemClickListener itemsOnClick,List<String> ci_pop) {
			super(context);
			this.ci_pop = ci_pop;
			
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mMenuView = inflater.inflate(R.layout.alert_dialog, null);
			btn_cancel = (TextView) mMenuView.findViewById(R.id.btn_cancel);
			//取消按钮
			btn_cancel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//销毁弹出框
					dismiss();
				}
			});
			
			insuranceview = (ListView) mMenuView.findViewById(R.id.insuranceview);
			insuranceview.setOnItemClickListener(itemsOnClick);
			
			adapter = new PopInsuranceAdapter();
			insuranceview.setAdapter(adapter);
			Utility.setListViewHeightBasedOnChildren(insuranceview);
			
			//设置SelectPicPopupWindow的View
			this.setContentView(mMenuView);
			//设置SelectPicPopupWindow弹出窗体的宽
			this.setWidth(LayoutParams.FILL_PARENT);
			//设置SelectPicPopupWindow弹出窗体的高
			this.setHeight(LayoutParams.WRAP_CONTENT);
			//设置SelectPicPopupWindow弹出窗体可点击
			this.setFocusable(true);
			//设置SelectPicPopupWindow弹出窗体动画效果
			this.setAnimationStyle(R.style.AnimBottom);
			//实例化一个ColorDrawable颜色为半透明
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			//设置SelectPicPopupWindow弹出窗体的背景
			this.setBackgroundDrawable(dw);
			//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
			mMenuView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					
					int height = mMenuView.findViewById(R.id.pop_layout).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});

		}
		
		class PopInsuranceAdapter extends BaseAdapter {
			@Override
			public int getCount() {
				return ci_pop == null ? 0 : ci_pop.size();
			}

			@Override
			public Object getItem(int arg0) {
				return ci_pop.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				return arg0;
			}

			@Override
			public View getView(int position, View view, ViewGroup parent) {
				if(view == null) {
					view = inflater.inflate(R.layout.pop_insurance_item, null);
				}
				TextView item_insurance = (TextView) view.findViewById(R.id.item_insurance);
				item_insurance.setText(ci_pop.get(position));
				return view;
			}
			
		}

	}

}
